const express = require("express");
const router = express.Router();
const models = require("../models");
const Op = models.Sequelize.Op; // 模糊查询的时候需要用到

// 分页列物资
router.get("/list", async function (req, res, next) {
  const where = {};
  const currentPage = parseInt(req.query.currentPage) || 1; // 分页参数
  const pageSize = parseInt(req.query.pageSize) || 10; // 分页参数
  const name = req.query.name;
  const type = req.query.type;
  const category = req.query.category;
  if (name) {
    where.name = {
      [Op.like]: "%" + name + "%",
    };
  }
  if (type) {
    where.type = {
      [Op.like]: type,
    };
  }
  if (category) {
    where.category = {
      [Op.like]: category,
    };
  }
  const result = await models.Good.findAndCountAll({
    order: [["id", "desc"]], // 根据某个字段进行排序， desc-降序 asc-升序
    where: where,
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
  });
  res.json({
    code: 200,
    msg: "操作成功",
    data: {
      total: result.count,
      currentPage: currentPage,
      pageSize: pageSize,
      data: result.rows,
    },
  });
});

// 新增物资
router.post("/", async function (req, res, next) {
  const where = {};
  const name = req.body.name;
  if (name) {
    where.name = {
      [Op.like]: "%" + name + "%",
    };
  }
  var data = await models.Good.findAndCountAll({
    where: where,
  });
  if (data.count > 0)
    return res.json({
      code: 400,
      msg: "物资名已存在，请另取物资名或者前往编辑物资",
    });
  await models.Good.create({
    name: name,
    price: req.body.price,
    unit: req.body.unit,
    goodsInfo: req.body.goodsInfo,
    timeBuying: req.body.timeBuying,
    inputPerson: req.body.inputPerson,
    inputTime: new Date(),
    inputNum: req.body.inputNum,
    stockNum: req.body.inputNum,
    totalInput: req.body.inputNum,
    type: req.body.type,
    category: req.body.category,
    critical: req.body.critical,
  });
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 根据id查询
router.get("/:id", async function (req, res, next) {
  const data = await models.Good.findByPk(req.params.id);
  res.json({
    code: 200,
    msg: "操作成功",
    data: data,
  });
});

// 修改物资
router.put("/", async function (req, res, next) {
  const result = await models.Good.findByPk(req.body.id);
  result.update(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 删除物资
router.delete("/:id", async function (req, res, next) {
  const result = await models.Good.findByPk(req.params.id);
  result.destroy(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

module.exports = router;
